package cn.turboinfo.fuyang.api.gateway.admin.controller.order;

import cn.turboinfo.fuyang.api.domain.admin.usecase.order.RefundOrderSearchUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.order.QRefundOrder;
import cn.turboinfo.fuyang.api.entity.common.pojo.order.RefundOrder;
import cn.turboinfo.fuyang.api.gateway.admin.fo.order.RefundOrderSearchFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.ResponseBodyWrapper;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.context.AdminRequestContext;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitDataFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.SortFO;
import cn.turboinfo.fuyang.api.gateway.web.framework.http.annotation.CompanyScope;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.request.QSort;
import net.sunshow.toolkit.core.qbean.helper.component.request.QBeanSearchHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

@Slf4j
@RequiredArgsConstructor
@Controller
@ResponseBodyWrapper
@RequestMapping("/admin/refundOrder")
public class RefundOrderController {
    private final RefundOrderSearchUseCase refundOrderSearchUseCase;

    @RequiresPermissions("adminRefund:list")
    @RequestMapping("/list")
    @CompanyScope
    public LimitDataFO<RefundOrder> list(@Valid RefundOrderSearchFO search, LimitFO page,
                                         SortFO sort, AdminRequestContext context) {

        QRequest request = QBeanSearchHelper.convertQRequest(search);

        if (sort.getSortFields() == null) {
            sort.setSortFields(new String[]{QRefundOrder.id + "|" + QSort.Order.DESC.name()});
        }

        if (context.getCompanyId() != null) {
            request.filterEqual(QRefundOrder.companyId, context.getCompanyId());
        }

        RefundOrderSearchUseCase.OutputData outputData = refundOrderSearchUseCase.execute(RefundOrderSearchUseCase.InputData
                .builder()
                .companyId(search.getCompanyId())
                .companyName(search.getCompanyName())
                .request(request)
                .requestPage(page.toQPage(sort.toQSortList()))
                .build());

        return LimitDataFO.fromQResponse(outputData.getQResponse());
    }
}
